package org.water.garden.msn.activity;

import org.water.garden.core.ImUtils;
import org.water.garden.msn.service.IMsnService;
import org.water.garden.msn.service.MsnServiceConstants;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.provider.Im.Account;
import android.util.Log;

/**
 * @author sshwsfc@gmail.com
 * 
 * Show MSN account status list for change
 */
public class AccountLogin extends Activity {

	protected static final String LOG_TAG = "AccountLogin";

	private Cursor accCur;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		accCur = ImUtils.queryAccount(getContentResolver(), getIntent()
				.getData(), new String[] { 
				Account._ID, Account.PROVIDER, Account.NAME, Account.PASSWORD, Account.ACTIVE });

		startService((new Intent())
				.setComponent(MsnServiceConstants.MSN_SERVICE_COMPONENT), null);
		bindMsnService();

		finish();
	}

	private void bindMsnService() {
		bindService((new Intent())
				.setComponent(MsnServiceConstants.MSN_SERVICE_COMPONENT),
				mConnection, 0);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(mConnection);
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		IMsnService MsnService;

		public void onServiceConnected(ComponentName className, IBinder service) {
			MsnService = IMsnService.Stub.asInterface(service);

			try {
				if (null != accCur && accCur.first()) {
					MsnService.login(accCur.getInt(0), accCur.getInt(1), accCur.getString(2), accCur.getString(3));
				} else {
					Log.e(LOG_TAG, "ERROR cann't find the account by Uri: "
							+ getIntent().getData().toString());
				}

			} catch (DeadObjectException ex) {
				Log.e(LOG_TAG, "caught " + ex);
			}
		}

		public void onServiceDisconnected(ComponentName className) {
		}
	};

}
